package com.zboot.zbootadmin.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: zyt
 * @Description:
 * @Date: Created in 17:37 2020/7/10
 */
@Slf4j
public class UploadUtils {

    public static JSONObject upload(MultipartFile file, String savePath) {
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File uploadDir = new File(savePath);
        String imgAddress = uploadDir.getAbsoluteFile()+"/"+fileName;
        File dest = new File(imgAddress);
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("dir",uploadDir.getAbsoluteFile().toString());
        jsonObject.put("fileName",fileName);
        log.info("路径为{}"+uploadDir.getAbsoluteFile().toString());
        log.info("文件名为{}"+fileName);
        return jsonObject;
    }
}
